#!/usr/bin/env python
import logging, sys
import os.path

def get_config(path):
	config = {}
	for cf in os.listdir(path):
		if cf.endswith(".yaml"):
			config[cf[:-5]] = yaml.load(open(os.path.join(path, cf), "rb"))
		elif not cf.startswith("."):
			config[cf] = get_config(os.path.join(path, cf))
	return config

if __name__ == "__main__":
	from optparse import OptionParser
	from paste import httpserver
	import yaml
	parser = OptionParser(version = "%prog version 2.0")
	parser.add_option("-p", "--port", help="Port", default=8080, dest="port")
	parser.add_option("--host", help="Host IP to listen on", default="127.0.0.1", dest="host")
	parser.add_option("-v", help="Verbosity, can be stacked", action="count", dest="verbosity")
	parser.add_option("-l", "--logfile", help="Log File", dest="logfp", default="STDERR")
	parser.add_option("-e", "--environment", help="Environment", dest="env", default="prod")
	(options, args) = parser.parse_args()
	if len(args) > 0:
		os.chdir(args[0])

	if options.logfp == "STDERR":
		logfp = sys.stderr
	else:
		print "Opening log file: %s" % options.logfp
		logfp = open(options.logfp, "a")

	if options.verbosity > 3:
		log_level = logging.DEBUG
	elif options.verbosity > 2:
		log_level = logging.INFO
	elif options.verbosity > 1:
		log_level = logging.WARNING
	else:
		log_level = logging.ERROR

	logging.basicConfig(level=log_level,
								format='%(asctime)s [%(name)-8s] %(levelname)-8s %(message)s',
								datefmt='%a, %d %b %Y %H:%M:%S',
								stream=logfp)
	log = logging.getLogger("marajo")

	sys.path.append(os.path.abspath("."))
	import marajo
	marajo.set_env(os.getcwd(), options.env)


	from marajo.appengine.ext.webapp import url_mapper, template
	template.template_dirs.append(os.path.abspath("./templates"))

	auth_type = marajo.config.get("auth_type", "basic")
	import marajo.appengine.handlers.auth
	__import__("marajo.appengine.handlers.auth.%s" % auth_type.lower())


	log.info("Starting Marajo Core")
	httpserver.serve(url_mapper.URLMapper(), host=options.host, port=int(options.port))
